package com.moive.news.tqnewsapplication.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mob.MobSDK;
import com.mob.tools.utils.UIHandler;
import com.moive.news.tqnewsapplication.R;
import com.moive.news.tqnewsapplication.base.BaseActivity;
import com.moive.news.tqnewsapplication.event.SenEvent;
import com.moive.news.tqnewsapplication.networks.BaseApi;
import com.moive.news.tqnewsapplication.okmanager.OkManagerCallback;
import com.moive.news.tqnewsapplication.utils.LogUtil;
import com.moive.news.tqnewsapplication.utils.PreferenceUtil;
import com.moive.news.tqnewsapplication.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.Call;

import static android.R.attr.action;

/**
 * Created by Administrator on 2017/12/12.
 */

public class LoginActivity extends BaseActivity implements PlatformActionListener, Handler.Callback {
    @BindView(R.id.login_phone01)
    TextView loginPhone01;
    @BindView(R.id.login_phone_edit)
    EditText loginPhoneEdit;
    @BindView(R.id.text001)
    TextView text001;
    @BindView(R.id.lgoin_getcode_edit)
    EditText lgoinGetcodeEdit;
    @BindView(R.id.login_button)
    Button loginButton;
    @BindView(R.id.login_weixin)
    RelativeLayout loginWeixin;
    @BindView(R.id.login_qq)
    RelativeLayout loginQq;
    @BindView(R.id.login_weibo)
    RelativeLayout loginWeibo;
    @BindView(R.id.login_send_text)
    Button loginSendText;
    @BindView(R.id.login_password_text)
    TextView loginPasswordText;
    @BindView(R.id.login_password_ll)
    LinearLayout loginPasswordLl;
    @BindView(R.id.login_code_text)
    TextView loginCodeText;
    @BindView(R.id.login_code_ll)
    LinearLayout loginCodeLl;
    @BindView(R.id.rigst)
    TextView rigst;
    @BindView(R.id.backpsd)
    TextView backpsd;
    private Resources resources;
    private TimeCount time;
    String phone = "", code = "", getcode = "";
    private static final String TAG = "LoginActivity";
    private static final int MSG_ACTION_CCALLBACK = 0;
    private ProgressDialog progressDialog;
    String isfrom = "";
    private int type = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        Intent intent = getIntent();
        if (intent != null) {
            isfrom = intent.getStringExtra("from");
        }
        loginPhoneEdit.setText(PreferenceUtil.getString("telephone", ""));
        resources = getResources();
        // 短信验证倒计时
        time = new TimeCount(60000, 1000);//构造CountDownTimer对象
        MobSDK.init(this);
    }

    @OnClick({R.id.login_send_text, R.id.login_button, R.id.login_weixin,
            R.id.login_qq, R.id.login_weibo, R.id.login_password_ll, R.id.login_code_ll, R.id.rigst, R.id.backpsd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_send_text:
                sendcode();
                break;
            case R.id.login_button:
                login();
                break;
            case R.id.login_weixin:
                Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                wechat.setPlatformActionListener(this);
                wechat.SSOSetting(true);
                authorize(wechat, 1);
                break;
            case R.id.login_qq:
                Platform qq = ShareSDK.getPlatform(QQ.NAME);
                qq.setPlatformActionListener(this);
                qq.SSOSetting(false);
                authorize(qq, 2);
                break;
            case R.id.login_weibo:
                Platform sina = ShareSDK.getPlatform(SinaWeibo.NAME);
                sina.setPlatformActionListener(this);
                sina.SSOSetting(false);
                authorize(sina, 3);
                break;
            case R.id.login_password_ll:
                type = 0;
                loginPasswordLl.setBackgroundResource(R.color.colorOrange);
                loginPasswordText.setTextColor(Color.parseColor("#FFFFFF"));
                loginCodeText.setTextColor(Color.parseColor("#504e4e"));
                lgoinGetcodeEdit.setHint("请输入密码");
                loginSendText.setVisibility(View.GONE);
                text001.setVisibility(View.GONE);
                loginCodeLl.setBackgroundResource(R.color.white);
                break;
            case R.id.login_code_ll:
                type = 1;
                loginPasswordLl.setBackgroundResource(R.color.white);
                loginPasswordText.setTextColor(Color.parseColor("#504e4e"));
                loginCodeText.setTextColor(Color.parseColor("#FFFFFF"));
                lgoinGetcodeEdit.setHint("请输入验证码");
                text001.setVisibility(View.VISIBLE);
                loginSendText.setVisibility(View.VISIBLE);
                loginCodeLl.setBackgroundResource(R.color.colorOrange);
                break;
            case R.id.rigst:
                startActivity(new Intent(LoginActivity.this, RegistActivity.class));
                break;
            case R.id.backpsd:
                startActivity(new Intent(LoginActivity.this, BackPwdActivity.class));
                break;
        }
    }

    //授权
    private void authorize(Platform plat, int type) {
        switch (type) {
            case 1:
                showProgressDialog(getString(R.string.opening_wechat));
                break;
            case 2:
                showProgressDialog(getString(R.string.opening_qq));
                break;
            case 3:
                showProgressDialog(getString(R.string.opening_blog));
                break;
        }
        if (plat.isAuthValid()) { //如果授权就删除授权资料
            plat.removeAccount(true);
            return;
        }
        plat.showUser(null);//授权并获取用户信息
    }

    private void login() {
        code = lgoinGetcodeEdit.getText().toString().trim();
        phone = loginPhoneEdit.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            if (type == 0) {
                ToastUtils.ShortToast("请输入密码！");
            } else {
                ToastUtils.ShortToast("请输入验证码");
            }
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.ShortToast("请输入电话号码！");
        }
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("telephone", phone);
        if (type == 0) {
            hashMap.put("password", code);
        } else {
            hashMap.put("code", code);
        }
        OkHttpUtils.post()
                .url(BaseApi.LOGIN)
                .params(hashMap)
                .build().execute(new OkManagerCallback(this) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.e(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        String data = jsonObject.getString("data");
                        PreferenceUtil.put("token", data);
                        if (TextUtils.isEmpty(isfrom)) {
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        } else {
                            EventBus.getDefault().post(new SenEvent("2"));
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        }
                        ToastUtils.ShortToast("登录成功");
                        finish();
                    } else {
                        ToastUtils.ShortToast(jsonObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public boolean handleMessage(Message msg) {
        hideProgressDialog();
        switch (msg.arg1) {
            case 1: { // 成功
                Toast.makeText(LoginActivity.this, "授权登陆成功", Toast.LENGTH_SHORT).show();
                //获取用户资料
                Platform platform = (Platform) msg.obj;
                String userId = platform.getDb().getUserId();//获取用户账号
                String userName = platform.getDb().getUserName();//获取用户名字
                String userIcon = platform.getDb().getUserIcon();//获取用户头像
                String userGender = platform.getDb().getUserGender(); //获取用户性别，m = 男, f = 女，如果微信没有设置性别,默认返回null
                Toast.makeText(LoginActivity.this, "用户信息为--用户名：" + userName + "  性别：" + userGender + "头像=" + userIcon + "用户id=" + userId, Toast.LENGTH_SHORT).show();
                LogUtil.i("lidaming", "用户信息为--用户名：" + userName + "  性别：" + userGender + "头像=" + userIcon + "用户id=" + userId);
            }
            break;
            case 2: { // 失败
                if (msg.obj.equals("cn.sharesdk.wechat.utils.WechatClientNotExistException")) {
                    ToastUtils.ShortToast("你未安装微信，无法登陆！");
                } else {
                    Toast.makeText(LoginActivity.this, "授权登陆失败", Toast.LENGTH_SHORT).show();
                }
            }
            break;
            case 3: { // 取消
                Toast.makeText(LoginActivity.this, "授权登陆取消", Toast.LENGTH_SHORT).show();
            }
            break;
        }
        return false;
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 1;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);   //发送消息
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 2;
        msg.arg2 = action;
        msg.obj = throwable;
        UIHandler.sendMessage(msg, this);
    }

    @Override
    public void onCancel(Platform platform, int i) {
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 3;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);
    }


    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {//计时完毕时触发
            loginSendText.setTextColor(resources.getColor(R.color.durk));
            loginSendText.setText("重新获取");
            loginSendText.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            loginSendText.setClickable(false);
            loginSendText.setTextColor(resources.getColor(R.color.grey_300));
            loginSendText.setText(millisUntilFinished / 1000 + "秒");
        }
    }

    private void sendcode() {
        phone = loginPhoneEdit.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.ShortToast("电话号码不能为空！");
            return;
        }
        time.start();
        OkHttpUtils.post()
                .url(BaseApi.SEND_CODE)
                .addParams("telephone", phone)
                .addParams("category", "1")
                .build().execute(new OkManagerCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
                ToastUtils.ShortToast(e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.e(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        getcode = jsonObject.getString("data");
                        ToastUtils.showLong(LoginActivity.this, getcode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //显示dialog
    public void showProgressDialog(String message) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(message);
        progressDialog.setCancelable(true);
        progressDialog.show();
    }

    //隐藏dialog
    public void hideProgressDialog() {
        if (progressDialog != null)
            progressDialog.dismiss();
    }


}
